import request from '@/utils/request'

export function createUploadVideo(fileName) {
  var fd = new FormData()
  fd.set('fileName', fileName)
  fd.set('name', fileName.split('.')[0])
  return request.post('http://store.91yunshi.com/storage/createUploadVideo', fd)
}

export function uploadAli(file, that) {
  let videoid
  const aliyun = new AliyunUpload.Vod({
    timeout: 60000,
    partSize: 1048576,
    parallel: 5,
    retryCount: 3,
    retryDuration: 2,
    region: 'cn-beijing',
    userId: 1274681370210884,
    // 添加文件成功
    addFileSuccess: function(uploadInfo) {
      self.uploadDisabled = false
      self.resumeDisabled = false
      self.statusText = '添加文件成功, 等待上传...'
      console.log('addFileSuccess: ' + uploadInfo.file.name)
    },
    // 开始上传
    onUploadstarted: function(uploadInfo) {
      that.videoUploadStatus = 1
      if (!uploadInfo.videoId) {
        createUploadVideo(file.name).then(({
          data
        }) => {
          const uploadAuth = data.uploadAuth
          const uploadAddress = data.uploadAddress
          const videoId = data.videoId
          videoid = data.videoId
          aliyun.setUploadAuthAndAddress(
            uploadInfo,
            uploadAuth,
            uploadAddress,
            videoId
          )
        })
        self.statusText = '文件开始上传...'
        console.log(
          'onUploadStarted:' +
          uploadInfo.file.name +
          ', endpoint:' +
          uploadInfo.endpoint +
          ', bucket:' +
          uploadInfo.bucket +
          ', object:' +
          uploadInfo.object
        )
      } else {
        // 如果videoId有值，根据videoId刷新上传凭证
        // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
        const refreshUrl =
          'http://store.91yunshi.com/storage/refreshUploadVideo?videoId=' +
          uploadInfo.videoId
        request.get(refreshUrl).then(({
          data
        }) => {
          const uploadAuth = data.uploadAuth
          const uploadAddress = data.uploadAddress
          const videoId = data.videoId
          videoid = data.videoId
          aliyun.setUploadAuthAndAddress(
            uploadInfo,
            uploadAuth,
            uploadAddress,
            videoId
          )
        })
      }
    },
    // 文件上传成功
    onUploadSucceed: function(uploadInfo) {
      console.log(
        'onUploadSucceed: ' +
        uploadInfo.file.name +
        ', endpoint:' +
        uploadInfo.endpoint +
        ', bucket:' +
        uploadInfo.bucket +
        ', object:' +
        uploadInfo.object
      )
      self.statusText = '文件上传成功!'
    },
    // 文件上传失败
    onUploadFailed: function(uploadInfo, code, message) {
      console.log(
        'onUploadFailed: file:' +
        uploadInfo.file.name +
        ',code:' +
        code +
        ', message:' +
        message
      )
      self.statusText = '文件上传失败!'
    },
    // 取消文件上传
    onUploadCanceled: function(uploadInfo, code, message) {
      console.log(
        'Canceled file: ' +
        uploadInfo.file.name +
        ', code: ' +
        code +
        ', message:' +
        message
      )
      self.statusText = '文件已暂停上传'
    },
    // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
    onUploadProgress: function(uploadInfo, totalSize, progress) {
      console.log(
        'onUploadProgress:file:' +
        uploadInfo.file.name +
        ', fileSize:' +
        totalSize +
        ', percent:' +
        Math.ceil(progress * 100) +
        '%'
      )
      const progressPercent = Math.ceil(progress * 100)
      that.percentage = progressPercent
      self.authProgress = progressPercent
      self.statusText = '文件上传中...'
    },
    // 上传凭证超时
    onUploadTokenExpired: function(uploadInfo) {
      const refreshUrl =
        'http://store.91yunshi.com/storage/refreshUploadVideo?videoId=' +
        uploadInfo.videoId
      request.get(refreshUrl).then(({
        data
      }) => {
        const uploadAuth = data.uploadAuth
        aliyun.resumeUploadWithAuth(uploadAuth)
        console.log(
          'upload expired and resume upload with uploadauth ' + uploadAuth
        )
      })
      self.statusText = '文件超时...'
    },
    // 全部文件上传结束
    onUploadEnd: function(uploadInfo) {
      console.log('onUploadEnd: uploaded all the files')
      that.question.videoAnalyze = 'http://store.91yunshi.com/storage/video/gaugua/' + videoid + '.mp4'
      that.video.sources.push({
        src: that.question.videoAnalyze,
        type: 'video/mp4'
      })
      that.videoUploadStatus = 2
      self.statusText = '文件上传完毕'
    }
  })
  var userData = '{"Vod":{"UserData":{"IsShowWaterMark":"true","Priority":"7"}}}'
  aliyun.addFile(file, null, null, null, userData)
  aliyun.startUpload()
  return aliyun
}
